package com.cartoonrabbit.wxapp.utils;

import net.coobird.thumbnailator.Thumbnails;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.springframework.http.MediaType;
import org.springframework.util.ClassUtils;
import org.springframework.util.ObjectUtils;
import org.springframework.util.ResourceUtils;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import java.io.*;
import java.util.UUID;

/**
 * 图片处理类
 */
public class ImageUtils {


    /**
     * 图片压缩
     */
    /**
     * 上传文件
     *
     * @param file 文件
     * @return
     */
    public static MultipartFile compressImage(MultipartFile file) throws Exception {
        // 判断上传文件是否为空
        if (null == file || 0 == file.getSize()) {
            return null;
        }

        // 拿到文件后缀名，例如：png
        String suffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".") + 1);
        // UUID 作为文件名
        String uuid = String.valueOf(UUID.randomUUID());
        // 新的文件名
        String fileName = PrimaryKeyUtils.getNo() + "/" + uuid + "." + suffix;
        /**
         * 判断是否是图片
         * 判断是否超过了 100K
         */
        if (isPicture(suffix) && (1024 * 1024 * 0.1) <= file.getSize()) {
            // 在项目根目录下的 upload 目录中生成临时文件
            File newFile = new File(System.getProperty("user.dir")+"/temp/" + uuid + "." + suffix);
            // 小于 1M 的
            if ((1024 * 1024 * 0.1) <= file.getSize() && file.getSize() <= (1024 * 1024)) {
                Thumbnails.of(file.getInputStream()).scale(1f).outputQuality(0.3f).toFile(newFile);
            }
            // 1 - 2M 的
            else if ((1024 * 1024) < file.getSize() && file.getSize() <= (1024 * 1024 * 2)) {
                Thumbnails.of(file.getInputStream()).scale(1f).outputQuality(0.2f).toFile(newFile);
            }
            // 2M 以上的
            else if ((1024 * 1024 * 2) < file.getSize()) {
                Thumbnails.of(file.getInputStream()).scale(1f).outputQuality(0.1f).toFile(newFile);
            }
            // 获取输入流
            FileInputStream input = new FileInputStream(newFile);
            // 转为 MultipartFile
            CommonsMultipartFile multipartFile = createMultipartFile(input,fileName);
            newFile.delete();
            return multipartFile;
        }
        // 不需要压缩，直接返回
        else {
            return file;
        }
    }



    /**
     * 判断文件是否为图片
     */
    public static boolean isPicture(String suffix) {
        boolean flag = false;
        if (ObjectUtils.isEmpty(suffix)) {
            return false;
        }
        String[] arr = {"jpg", "jpeg","png", "bmp", "tiff","jfif"};
        for (String item : arr) {
            if (item.equals(suffix)) {
                flag = true;
                break;
            }
        }
        return flag;
    }

    /**
     *
     * @param inputStream inputStream
     * @param fileName    fileName
     * @return FileItem
     */
    public static CommonsMultipartFile createMultipartFile(InputStream inputStream, String fileName) {
        FileItemFactory factory = new DiskFileItemFactory(16, null);
        String textFieldName = "file";
        FileItem item = factory.createItem(textFieldName, MediaType.IMAGE_PNG_VALUE, true, fileName);
        int bytesRead = 0;
        byte[] buffer = new byte[8192];
        OutputStream os = null;
        //使用输出流输出输入流的字节
        try {
            os = item.getOutputStream();
            while ((bytesRead = inputStream.read(buffer, 0, 8192)) != -1) {
                os.write(buffer, 0, bytesRead);
            }
            inputStream.close();
        } catch (IOException e) {
            throw new IllegalArgumentException("文件上传失败");
        } finally {
            if (os != null) {
                try {
                    os.close();
                } catch (IOException e) {

                }
            }
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                }
            }
        }

        return new CommonsMultipartFile(item);
    }

    //判断媒体类型
    public static String getMediaType(String fileName){
        String[] split = fileName.split(".");

        if (split!=null&&split.length>0){
            String suffix=split[split.length-1];
            if (suffix.equals("jpg")||suffix.equals("jpeg")){
                return MediaType.IMAGE_JPEG_VALUE;
            }
            if (suffix.equals("png")){
                return MediaType.IMAGE_PNG_VALUE;
            }
            if (suffix.equals("gif")){
                return MediaType.IMAGE_GIF_VALUE;
            }
        }
        return MediaType.MULTIPART_FORM_DATA_VALUE;
    }


}
